﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using EfSearchModel.Model;
using EfSearchModel.Binders;

namespace Resto.CostControl.Core
{
    /// <summary>
    /// 对SearchModel做为Action参数的绑定
    /// </summary>
    public class DWZQueryModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = (DWZQueryModel)(bindingContext.Model ?? new DWZQueryModel());
            var dict = controllerContext.HttpContext.Request.Params;
            var keys = dict.AllKeys.Where(c => c.StartsWith("["));//我们认为只有[开头的为需要处理的
            if (keys.Count() != 0)
            {
                foreach (var key in keys)
                {
                    if (!key.StartsWith("[")) continue;
                    var val = dict[key];
                    //处理无值的情况
                    if (string.IsNullOrEmpty(val)) continue;
                    SearchModelBinder.AddSearchItem(model, key, val);
                }
            }
            else
            {
                // 快速查询条件
                if (!string.IsNullOrEmpty(dict["qtype"]) && !string.IsNullOrEmpty(dict["keywords"]))
                {
                    foreach (var field in dict["qtype"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                    {
                        model.Items.Add(new ConditionItem
                        {
                            Field = field,
                            Method = QueryMethod.Like,
                            Value = dict["keywords"],
                            OrGroup = "QuickQuery"
                        });
                    }
                }
            }

            return model;
        }
    }
}
